<template>
	<view class="main animated fadeIn faster">
		<TitleBarVue :title="title"/>
		<view class="bg-fff rounded30 px-2" style="padding-top: 190rpx; padding-bottom: 110rpx;">
			<view class="mb-4">
				<view class="d-flex d-flex-middle d-flex-between mb-1">
					<view class="d-flex d-flex-middle d-flex-between" style="width: 100%;">
						<view class="img-bg d-flex d-flex-center d-flex-middle mr-1" style="position: relative;">
							<image @click="touser(mainComment.commentUid)" :src="mainComment.avatar" class="img-bg-img rounded" mode="aspectFill" style="width: 100rpx; height: 100rpx;"></image>
							 <image v-if="mainComment.dressedVoMap && mainComment.dressedVoMap['1']" class="avatar-frame" :src="mainComment.dressedVoMap['1'].icon"></image>
							
						</view>
						<view style="flex: 1;" @click="editParams(mainComment.nickname, mainComment.blogId, mainComment.id)">
							<view class="horizontal-container ml-1">
							<view class="mb-1 font30">{{mainComment.nickname}}</view>
							<view class="sex ml-1  " style="width: 30rpx; height: 30rpx; margin-bottom: 25rpx; ">
								<image v-if="mainComment.gender === 1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%94%B7.png" style="width: 100%; height: 100%;"></image>
								<image v-if="mainComment.gender === 2" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203404.png" style="width: 100%; height: 100%;"></image>
							</view>
							</view>
							
							<view class="font24 color999">{{mainComment.time}}{{mainComment.ipProvince? ' · ' + mainComment.ipProvince.slice(0, 2) : '· 未知'}}</view>
						</view>
						<view class="d-flex">
							<image @click="LikeStatus" v-if="!mainComment.favorFlag" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%88%B1%E5%BF%83.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<image @click="LikeStatus" v-if="mainComment.favorFlag" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/heart-3-fill.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<view class="mr-2">{{mainComment.favorCount}}</view>
						</view>
					</view>
				</view>
				<view class="pb-2 ml-1" style="padding-left: 52px;" @click="editParams(mainComment.nickname, mainComment.blogId, mainComment.id)">
					<view class="font26 mb-2">{{mainComment.commentContent}}</view>
				</view>
			</view>
			
			<!-- 这是二级评论，三级评论在他的子集下面 -->
			<view class="tab rounded40 mb-4" style="background: #cfeffb;" id="comment">全部评论</view>
			<view class="pb-2" v-for="(i, index) in commentList" :key="i.id">
				<view class="d-flex d-flex-middle d-flex-between mb-1">
					<view class="d-flex d-flex-middle d-flex-between" style="width: 100%;">
						<view @click="touser(i.commentUid)" class="img-bg d-flex d-flex-center d-flex-middle mr-1" style="position: relative;">
							<image :src="i.avatar" class="img-bg-img rounded" mode="aspectFill" style="width: 100rpx; height: 100rpx;"></image>
							 <image v-if="i.dressedVoMap && i.dressedVoMap['1']" class="avatar-frame" :src="i.dressedVoMap['1'].icon"></image>
							
							
							
						</view>
						<view style="flex: 1;" @click="editParams(i.nickname, i.blogId, i.id, index)">
							<view class="horizontal-container ml-1">
							<view class="mb-1 font30">{{mainComment.nickname}}</view>
							<view class="sex ml-1  " style="width: 30rpx; height: 30rpx; margin-bottom: 25rpx; ">
								<image v-if="mainComment.gender === 1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%94%B7.png" style="width: 100%; height: 100%;"></image>
								<image v-if="mainComment.gender === 2" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203404.png" style="width: 100%; height: 100%;"></image>
							</view>
							</view>
							<view class="font24 color999">{{i.time}}{{i.ipProvince? ' · ' + i.ipProvince.slice(0, 2) : '· 未知'}}</view>
						</view>
						<view class="d-flex">
							<image v-show="!i.favorFlag" @click="changeLikeStatus(index, i.blogId)" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%88%B1%E5%BF%83.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<image v-show="i.favorFlag" @click="changeLikeStatus(index, i.blogId)" class="mr-1" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/heart-3-fill.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<view class="mr-2">{{i.favorCount}}</view>
						</view>
					</view>
				</view>
				<view class="ml-1" style="padding-left: 52px;" @click="editParams(i.nickname, i.blogId, i.id, index)">
					<view class="font26 mb-2">{{i.commentContent}}</view>
				</view>
				<view class="pl-1 py-1 mr-2" style="margin-left: 52px; background: #f6f6f6; transition: all 0.3s ease;" v-show="i.sub? i.sub.length : 0">
					<view v-for="(item, dex) in i.sub" :key="item" v-show="dex<i.showCommentLength">
						<view @click="editThirdParams(item.nickname, item.blogId, index, dex)" class="mb-1"><view style="color: #47c3ff;">{{item.nickname}}<view style="display: inline-block; color: #231816; margin: 0 4rpx;">回复</view>{{i.nickname}}：<view style="color: #231816; display: inline-block;">{{item.commentContent}}</view></view></view>
					</view>
				</view>
				<view class="ml-1 d-flex d-flex-middle mt-1" style="padding-left: 52px;">
					<view class="d-flex d-flex-middle mr-5" v-show="i.hasSub && (i.showCommentLength? Number(i.totalCommentCount) > i.showCommentLength : 1)">
						<view class="font24 color999" @click="moreComment(i.id,index)">{{i.pageIndex? '展开更多' : '展开'+i.totalCommentCount+'条回复'}}</view>
						<text class="iconfont icon-youjiantou color999"></text>
					</view>
					<view class="d-flex d-flex-middle" @click="retract(index)" v-show="i.pageIndex || i.sub? i.sub.length : 0">
						<view class="color999 font24">收起</view>
						<text class="iconfont icon-youjiantou color999" style="margin-left: 3px; transform: rotate(-90deg)"></text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="position-fixed top-0 left-0 right-0" style="bottom: 0; background: transparent;" @click="closePopup" v-show="focus"></view>
		
		<view class="d-flex-btn z-index-10 position-fixed w-100 bottom-0 bg-fff py-2" :style="{'bottom':keyboardHeight+'px'}">
			<!-- #ifdef APP -->
			<input class="uni-input font26" @input="oninput" :focus="focus" @focus="onfocus" :placeholder="placeholder" v-model="inputVal" style="flex: 1;"/>
			<!-- #endif -->
			<!-- #ifndef APP -->
			<input class="uni-input font26" :adjust-position="false" @input="oninput" :focus="focus" @focus="onfocus" :placeholder="placeholder" v-model="inputVal" style="flex: 1;"/>
			<!-- #endif -->
			<text v-show="!focus" class="mx-2 iconfont icon-bianji color6d"></text>
			<view v-show="focus" @click="Comment" class="mx-2 colorfff px-2 py-1 rounded40" :style="{'background': sentBtnStyly}">发送</view>
		</view>
		<view class="loadmore position-relative text-center" v-if="showLoadMore" style="bottom: 110rpx;">{{loadMoreText}}</view>
	</view>
</template>

<script>
	import TitleBarVue from '../../components/TitleBar.vue';
	import store from '@/store/index.js';
	import { blogApi } from '../../http/blogApi';
	import { TaskApi } from '../../http/taskApi';
	export default {
		data() {
			return {
				title: '评论详情',
				commentList: [],
				mainComment: [],
				focus: false,
				keyboardHeight: 0,
				inputVal: "",
				max: false,
				showLoadMore: false,
				FavorFlag: null,
				showCommentLength: 3,
				isCompleted: false,
				placeholder: "友善评论的人都是最可爱哒",
				loadMoreText: "加载中...",
				sentBtnStyly: "rgba(69, 199, 255, .7)",
				subPageIndex: 1,
				subPageSize: 10,
				commentIndex: null,
				ThirdCommentIndex: null,
				isLastComment: false,
				params: {
					commentId: null,
					pageIndex: 1,
					pageSize: 10,
				},
				commentParams: {
					blogId: null,
					commentContent: null,
					commentIdRef: null
				},
				ShowParams: {
					commentId: null,
					pageIndex: 1,
					pageSize: 3
				}
			}
		},
		components: {TitleBarVue},
		methods: {
			goBack() {
				uni.navigateTo({
				    delta: 1
				});
			},
			// 检测键盘高度
			listenKeyboardHeightChange() {
				uni.onKeyboardHeightChange(res => {
					//#ifdef APP
						if(res.height === 0) {
							this.commentParams.commentIdRef = this.mainComment.id
							this.commentParams.blogId = this.mainComment.blogId
							this.placeholder = "友善评论的人都是最可爱哒"
							this.focus = false
							setTimeout(() => {
								this.commentIndex = null
								this.isLastComment = false
								this.params.commentId = this.mainComment.id
							},500)
						}
					// #endif
					// #ifndef APP
						this.keyboardHeight = res.height
					// #endif
					
					//#ifdef MP-WEIXIN
						this.keyboardHeight = res.height
						if(res.height === 0) {
							this.commentParams.commentIdRef = this.mainComment.id
							this.commentParams.blogId = this.mainComment.blogId
							this.placeholder = "友善评论的人都是最可爱哒"
							this.focus = false
							setTimeout(() => {
								this.commentIndex = null
								this.isLastComment = false
								this.params.commentId = this.mainComment.id
							},500)
						}
					// #endif
				});
			},
			// 查询二级评论
			async BlogCommentList() {
				let res = await blogApi.BlogCommentList(this.params)
				if(res.records.length < res.size) {
					this.max = true
				}
				this.commentList = this.commentList.concat(res.records)
			},
			// 查询所有的第一条子评论
			async FirstComment(params) {
				let res = await blogApi.BlogCommentList(params)
				return res.records[0]
			},
			// 修改二级评论参数
			editParams(nickname, blogId, id, index) {
				this.focus = true
				this.commentParams.blogId = blogId
				this.commentParams.commentIdRef = id
				this.params.commentId = id
				this.placeholder = "回复 " + nickname + "："
				if(index != undefined) {
					this.commentIndex = index
				}
			},
			// 修改三级评论参数
			editThirdParams(nickname, blogId, index, dex) {
				if(dex !== null) {
					this.isLastComment = true;
					this.ThirdCommentIndex = dex
				}
				this.commentIndex = index
				this.focus = true
				this.commentParams.blogId = blogId
				this.commentParams.commentIdRef = this.commentList[index].sub[dex].id
				this.params.commentId = this.commentList[index].sub[dex].id
				this.placeholder = "回复 " + nickname + "："
			},
			checkRealNaem(){//判断是否实名
				// if(this.$store.state.user.realName==''||this.$store.state.user.realName==null){
				// 	return false					
				// }else{	
				// 	return true
				// }			
				return true
			},
			// 评论博客
			async Comment() {
				if(this.checkRealNaem()){
				if(this.inputVal == "") {
					uni.showToast({
						icon: 'none',
						title: '评论不能为空哦',
						duration: 1500
					})
					return
				}
				this.inputVal = ""
				let res = await blogApi.Comment(this.commentParams)
				if(this.commentIndex === null) {
					let params = {
						commentId: this.params.commentId,
						pageIndex: 1,
						pageSize: 1
					}
					setTimeout(() => {
						this.FirstComment(params).then((result) => {
							this.commentList.unshift(result)
							this.getTaskList(20);
						})
						console.log("这是二级评论");
					}, 300)
				} else {
					if(!this.isLastComment) {
						let params = {
							commentId: this.params.commentId,
							pageIndex: 1,
							pageSize: 1
						}
						setTimeout(() => {
							this.FirstComment(params).then((result) => {
								if(!this.commentList[this.commentIndex].sub) {
									this.commentList[this.commentIndex].sub = []
								}
								if(!this.commentList[this.commentIndex].showCommentLength) {
									this.commentList[this.commentIndex].showCommentLength = 1
								} else {
									this.commentList[this.commentIndex].showCommentLength++
								}
								if(!this.commentList[this.commentIndex].pageIndex) {
									this.commentList[this.commentIndex].pageIndex = 1
								}
								this.commentList[this.commentIndex].sub.unshift(result)
								this.commentList[this.commentIndex].totalCommentCount++
							})
							console.log("这是三级评论");
						}, 300)
					} else {
						let params = {
							commentId: this.params.commentId,
							pageIndex: 1,
							pageSize: 1
						}
						setTimeout(() => {
							this.FirstComment(params).then((result) => {
								if(!this.commentList[this.commentIndex].showCommentLength) {
									this.commentList[this.commentIndex].showCommentLength = 1
								} else {
									this.commentList[this.commentIndex].showCommentLength++
								}
								if(!this.commentList[this.commentIndex].pageIndex) {
									this.commentList[this.commentIndex].pageIndex = 1
								}
								this.commentList[this.commentIndex].sub.splice(this.ThirdCommentIndex+1, 0, result)
								this.commentList[this.commentIndex].totalCommentCount++
							})
							console.log("这是评论三级评论的评论");
						}, 300)
					}
				}
				 }else{
					uni.showModal({
					  content: '你还没有完成实名认证，请先完成实名认证？',
					  confirmText: '去实名',
					  success: (res) => {
					    if (res.confirm) {  
					     uni.navigateTo({
					         url: `/pagesApp/RealName/RealName`
					     });
					    } else if (res.cancel) {
												 
					      // console.log('用户点击取消');
					      // 不执行任何操作，用户取消退出
					    }
					  }
					});
				}	
			},
			// 使用递归取出所有的评论节点放入同一层级
			extractAllSubs(item, dex) {
				if(!this.commentList[dex].isCompleted) {
					if (item.sub&&item.sub.length>0) {
						this.commentList[dex].sub.push(item);
						let list = item.sub;
						item.sub = null;
					    list.forEach(subItem => {
					        this.extractAllSubs(subItem,dex);
					    });
					} else {
						this.commentList[dex].sub.push(item)
					}
				}
			},
			// 展开更多评论
			async showMoreComment(dex) {
				let commentLength = 3;
				if(this.commentList[dex].showCommentLength){
					commentLength = this.commentList[dex].showCommentLength + 10;
				}
				while(this.commentList[dex].sub.length < commentLength){
					this.ShowParams.pageIndex = this.commentList[dex].pageIndex;
					let res = await blogApi.QueryThirdComment(this.ShowParams)
					if(res.records.length==0) {
						this.commentList[dex].isCompleted = true
						break;
					}else{
						this.commentList[dex].pageIndex++;
					}
					res.records.forEach((item) => {
						this.extractAllSubs(item,dex)
					});
				}
				if(this.commentList[dex].sub.length>=this.commentList[dex].showCommentLength||!this.commentList[dex].showCommentLength){
					this.commentList[dex].showCommentLength = commentLength;
				}
				this.commentList[dex].sub = this.commentList[dex].sub.filter((obj, index, self) => {
				    return self.findIndex(item => item.id === obj.id) === index;
				});
			},
			moreComment(id, dex) {
				if(!this.commentList[dex].sub) {
					this.commentList[dex].sub = [];
					this.commentList[dex].pageIndex = 1;
				}
				if(!this.commentList[dex].pageIndex) {
					this.commentList[dex].pageIndex = 1;
				}
				// 判断commentlist有没有sub，没有sub就是第一次展开，就请求一次
				if((!this.commentList[dex].showCommentLength)||(this.commentList[dex].sub.length < this.commentList[dex].showCommentLength+10)){
					this.ShowParams.commentId = id;
					this.showMoreComment(dex)
				}else if(this.commentList[dex].sub.length >= this.commentList[dex].showCommentLength+10){
					this.commentList[dex].showCommentLength+=10
				}
			},
			// 收起评论
			retract(dex) {
				this.commentList[dex].sub = []
				this.commentList[dex].showCommentLength = null
				this.commentList[dex].pageIndex = null
				this.commentList[dex].isCompleted = false
			},
			// 二级、三级评论（点赞 / 取消点赞）
			async changeLikeStatus(index, blogId) {
				this.commentList[index].favorFlag = this.commentList[index].favorFlag? 0 : 1
				if(this.commentList[index].favorFlag) {
					this.commentList[index].favorCount++
				} else {
					this.commentList[index].favorCount--
				}
				let params = {
					toCommentId: this.commentList[index].id,
					flag: this.commentList[index].favorFlag? true : false,
					blogId: blogId
				}
				let res = await blogApi.BlogCommentFavor(params)
			},
			// 一级评论的（点赞 / 取消点赞）
			async LikeStatus() {
				this.mainComment.favorFlag = this.mainComment.favorFlag? 0 : 1
				if(this.mainComment.favorFlag) {
					this.mainComment.favorCount++
				} else {
					this.mainComment.favorCount--
				}
				this.FavorFlag = this.mainComment.favorFlag? 1 : 0
				let params = {
					toCommentId: this.mainComment.id,
					flag: this.mainComment.favorFlag? true : false,
					blogId: this.mainComment.blogId
				}
				let res = await blogApi.BlogCommentFavor(params)
				uni.setStorageSync('FavorData', {
					id: this.mainComment.id,
					flag: this.mainComment.favorFlag? true : false
				});
			},
			// 关闭遮罩层
			closePopup() {
				//#ifdef MP-WEIXIN
					this.focus = false
				// #endif
			},
			// 跳转至用户主页
			touser(uid){
				if(uid === this.$store.state.user.uid){
					uni.switchTab({
					    url: '/pages/user/user'
					});
					return
				}
				uni.navigateTo({
				    url: `/pagesMain/HomePage/HomePage?id=${uid}`
				});
			},
			// 检测输入状态
			oninput() {
				this.commentParams.commentContent = this.inputVal
				if(this.inputVal != "") {
					this.sentBtnStyly = "rgba(69, 199, 255, 1)"
				} else {
					this.sentBtnStyly = "rgba(69, 199, 255, .7)"
				}
			},
			// 输入框获取焦点的时候
			onfocus() {
				this.focus = true
				if(!this.focus) {
					this.placeholder = "回复 " + this.mainComment.nickname + "："
				}
			},
			async getTaskList(taskid) {
				let params = {
					id: taskid
				}
				let res = await TaskApi.getTaskList(params)
				if(res.records[0].finishFlag) return
				if(!res.records[0].receiveFlag) {
					this.receiveTask(taskid).then(() => {
						this.finishTask(taskid);
					})
				} else {
					this.finishTask(taskid);
				}
			},
			async receiveTask(id) {
				let params = {
					taskId: id
				}
				let res = await TaskApi.ReceiveTask(params)
				console.log('领取完成！');
			},
			async finishTask(id) {
				let params = {
					taskId: id
				}
				let res = await TaskApi.FinishTask(params);
				console.log('任务完成！');
			}
		},
		// 加载更多
		onReachBottom() {
			if (this.max) {
				return;
			} else {
				this.params.pageIndex++
				this.BlogCommentList()
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			setTimeout(() => {
				this.commentList = []
				this.BlogCommentList()
				this.commentParams.commentIdRef = this.mainComment.id
				this.commentParams.blogId = this.mainComment.blogId
				this.params.commentId = this.mainComment.id
				this.params.pageIndex = 1
				this.placeholder = "友善评论的人都是最可爱哒"
				this.inputVal = ""
				this.focus = false
				this.max = false
				this.isLastComment = false
				this.commentIndex = null
				uni.stopPullDownRefresh();
			}, 300);
		},
		// 初始化数据
		onLoad: function(option) {
			this.mainComment = JSON.parse(option.data)
			console.log(this.mainComment);
			this.params.commentId = this.mainComment.id
			this.commentParams.blogId = this.mainComment.blogId
			this.commentParams.commentIdRef = this.mainComment.id
			this.BlogCommentList()
			this.listenKeyboardHeightChange();
		},
		onUnload() {
		    uni.offKeyboardHeightChange(); // 页面卸载时移除键盘高度变化的监听
		}
	}
</script>

<style scoped lang="scss">
	.horizontal-container {
	  display: flex;
	  flex-direction: row;
	  align-items: center; /* 垂直居中 */
	 
	}
	.avatar-frame {
	  position: absolute;
	
	   width: 120rpx; /* 比头像大 20rpx */
	   height: 120rpx; /* 比头像大 20rpx */
	  z-index: 2;  /* 调整层级 */
	  pointer-events: none;
	}
.main {
	background: #fff;
	overflow: hidden;
	.content {
		width: 100%;
		overflow: hidden;
	}
}
.uni-input {
	margin-left: 20rpx;
	background: #e6f5fb;
	color: #231816;
	border-radius: 50rpx;
	padding-left: 40rpx;
	height: 70rpx;
}
.tab {
	background-color: #cfeffb;
	border: 1px solid #7ed1f9;
	color: #57c3fd;
	padding: 12rpx 30rpx;
	display: inline-block;
}
</style>
